const md5 = require('../util/md5')
const Admin = require('../models/index/Admin')

// 登录
exports.login = async function (username, password) {
  password = md5(password)
  const result = await Admin.findOne({
    where: {
      username,
      password
    },
    attributes: { exclude: ['password'] }
  })
  if (result && result.username === username) {
    return result.toJSON()
  }
  // 用户不存在
  return null
}

// 添加管理员
exports.addAdmin = async function (adminObj) {
  adminObj.password = md5(adminObj.password)
  const ins = await Admin.create(adminObj)
  return ins.toJSON()
}

// 删除管理员
exports.deleteAdmin = async function (adminId) {
  const result = await Admin.destroy({
    where: {
      id: adminId
    }
  })
  return result
}

// 修改用户密码
exports.updateAdmin = async function (id, adminObj) {
  if (adminObj.password) {
    adminObj.password = md5(adminObj.password)
  }
  const result = await Admin.update(adminObj, {
    where: {
      id
    },
    attributes: { exclude: ['password'] }
  })
  return result
}

// 获取所有管理员
exports.getAdmins = async function () {
  const result = await Admin.findAll({
    attributes: { exclude: ['password'] }
  })
  return JSON.parse(JSON.stringify(result))
}

// 获取用户信息
exports.getAdmin = async function (id) {
  const result = await Admin.findByPk(id, {
    attributes: {
      exclude: ['password']
    }
  })
  return JSON.parse(JSON.stringify(result))
}
